import json
import logging
from django.http import JsonResponse
from django.shortcuts import render
from django.db import transaction
from django.views import View
from django.db.models import Q
from aijiazufang.utils.view import LoginRequiredMixin
from orders.models import Order
from homes.models import House
from django.utils import timezone
#指定日志对象
logger = logging.getLogger('django')


class OrderCommentView(LoginRequiredMixin, View):
    '''评论订单'''
    def put(self, request, order_id):
        #接收参数
        json_dict = json.loads(request.body.decode())
        comment = json_dict.get('comment')

        if not comment:
            return JsonResponse({'errno': 4002, 'errmsg': '缺少必传参数comment'})

        try:
            order = Order.objects.get(order_id=order_id)
            order.comment = comment
            order.status = Order.ORDER_STATUS['COMPLETE']
            order.save()

        except Exception as e:
            return JsonResponse({'errno': 4001, 'errmsg': '查询订单失败或保存订单评论信息失败'})

        return JsonResponse({'errno': 0, 'errmsg': '评论成功'})


class OkorNoView(LoginRequiredMixin, View):
    """接受或拒绝订单"""

    def put(self, request, order_id):

        # 接受参数
        json_dict = json.loads(request.body)
        action = json_dict.get('action')
        reason = json_dict.get('reason')

        # 检验参数
        if not action:
            return JsonResponse({'errno': 4103,
                                 'errmsg': 'action参数缺少'})
        if not order_id:
            return JsonResponse({'errno': 4103,
                                 'errmsg': '参数错误'})

        # 获取该房屋的状态
        # try:
        #     order_status = Order.objects.get(user=request.user, order_id=order_id)
        #     if order_status.status == 5 or order_status.status == 6:
        #         order_status.status = 0
        #         order_status.save()
        # except Exception as e:
        #     return JsonResponse({'errno':4004,
        #                          'errmsg':'修改状态失败'})

        # 如果接受订单
        if action == 'accept':
            # 修改数据库订单状态
            try:
                order = Order.objects.get(order_id=order_id)
                order.status = Order.ORDER_STATUS['WAIT_COMMENT']
                order.save()
            except Exception as e:
                return JsonResponse({'errno': 4004,
                                     'errmsg': '修改数据库失败'})
        # 拒绝订单
        elif action == 'reject':
            try:
                order = Order.objects.get(order_id=order_id)
                order.comment = reason
                order.status = Order.ORDER_STATUS['REJECTED']
                order.save()
            except Exception as e:
                return JsonResponse({'errno': 4004,
                                     'errmsg': '修改数据库失败'})
        else:
            return JsonResponse({'errno': 4103,
                                 'errmsg': '参数错误'})

        return JsonResponse({'errno': 0,
                             'errmsg': 'ok'})


class UserOrderView(View):
    # 房源列表页

    def get(self, request):
        # 提供房源列表页
        # 获取参数：

        user_role = request.GET.get('role')
        order_data = []
        # 判断role参数,房客时
        if user_role == 'custom':
            # 用户已登录，查询订单信息
            try:
                orders = Order.objects.filter(user=request.user)
                for order in orders:
                    time = str(order.create_time)[:-22]
                    order_data.append({"amount": order.amount,
                                       "comment": order.comment,
                                       "ctime": time,
                                       "days": order.days,
                                       "end_date": order.end_date,
                                       "img_url": order.house.index_image_url,
                                       "order_id": order.order_id,
                                       "start_date": order.begin_date,
                                       "status": order.status,
                                       "title": order.house.title
                                       })
            # 数据库出错
            except Exception as e:
                return JsonResponse({'errmsg': '4001',
                                     'errno': '数据处理失败'})

        elif user_role == 'landlord':
            # 用户已登录，查询订单信息
            try:
                houses = House.objects.filter(user=request.user)
                for house in houses:
                    orders = Order.objects.filter(house=house)
                    for order in orders:
                        time = str(order.create_time)[:-22]
                        order_data.append({"amount": order.amount,
                                           "comment": order.comment,
                                           "ctime": time,
                                           "days": order.days,
                                           "end_date": order.end_date,
                                           "img_url": order.house.index_image_url,
                                           "order_id": order.order_id,
                                           "start_date": order.begin_date,
                                           "status": order.status,
                                           "title": order.house.title
                                           })
                # 数据库查询出错
            except Exception as e:
                return JsonResponse({'errmsg': '4001',
                                     'errno': '数据处理失败'})
        else:
            return JsonResponse({"errmsg": "参数错误",
                                 "errno": "4004"})

        data = {'orders': order_data}
        return JsonResponse({'data': data,
                             "errmsg": "OK",
                             "errno": "0"
                             })

    def post(self, request):
        """
        添加订单
        :param request: 请求对象
        :return: 响应对象
        """
        # 提取信息
        json_dict = json.loads(request.body.decode())
        house_id = json_dict.get('house_id')
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')
        # 校验参数
        if not all([house_id, start_date, end_date]):
            return JsonResponse({"errmsg": "数据错误",
                                 "errno": "4004"})
        # 判断房源是否已经生成订单:
        try:
            order = Order.objects.filter(house_id=house_id)
            if order:
                return JsonResponse({'errmsg': '房源已出租',
                                     'errno': 4003})
        except BaseException as error:
            logger.error(error)
            return JsonResponse({'errmsg': '连接数据库失败',
                                 'errno': 4001})

        # 查询房屋信息:
        houses = House.objects.get(id=house_id)
        if not houses:
            return JsonResponse({"errmsg": "数据错误",
                                 "errno": 4004})
        # 计算天数:
        days = int(end_date.replace('-', '')) - int(start_date.replace('-', ''))
        # 判断天数是否满足酒店要求
        if not days >= houses.min_days:
            return JsonResponse({"errmsg": "不满足时间要求",
                                 "errno": "4103"})
        if not houses.max_days == 0:
            if days > houses.max_days:
                return JsonResponse({"errmsg": "不满足时间要求",
                                     "errno": "4103"})
        # 生成订单ID:
        order_id = timezone.localtime().strftime('%Y%m%d%H%M%S') + ('%09d' % request.user.id)
        # 将订单写入数据库:
        try:
            Order.objects.create(
                order_id=order_id,
                user=request.user,
                house=houses,
                begin_date=start_date,
                end_date=end_date,
                days=days,
                house_price=houses.price,
                amount=houses.price * days,
                status=Order.ORDER_STATUS['WAIT_ACCEPT']
            )
        except BaseException as error:
            logger.error(error)
            return JsonResponse({'errno': 4301, 'errmsg': '下单失败'})
        return JsonResponse({"data": {"order_id": order_id},
                             "errno": "0",
                             "errmsg": "下单成功"})
